package com.neu.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.config.DataListenerFactory;
import com.neu.entity.DTO.InviteProjectUser;
import com.neu.entity.DTO.ProjectDTO;
import com.neu.entity.DTO.RemoveUserProject;
import com.neu.entity.DTO.TaskDTO;
import com.neu.entity.Project;
import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.service.ProjectService;
import com.neu.utils.excel.DataListener;
import com.neu.utils.excel.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/projects")
@Tag(name = "项目管理")
public class ProjectController {
    @Autowired
    ProjectService projectService;
    @Autowired
    private DataListenerFactory dataListenerFactory;

    @PostMapping("/page")
    @Parameters({
            @Parameter(name = "pageNum", description = "页码", required = true),
            @Parameter(name = "pageSize", description = "每页显示数量", required = true)
    })
    @Operation(summary = "分页查询")
    public Result page(@RequestParam Integer pageNum,
                       @RequestParam Integer pageSize) {
        PageBean<Project> pagelist = projectService.pagelist(pageNum, pageSize);
        //如果当前页码值大于总页数，返回最后一页数据
        if (pageNum > pagelist.getTotalPage()) {
            pagelist = projectService.pagelist((int) pagelist.getTotalPage(), pageSize);
        }
        return Result.success(pagelist);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除项目")
    public Result delete(@RequestBody ProjectDTO projectDTO) {
        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")&&!permissions.contains("ROLE_admin")) {
            return Result.error("无权限删除项目!");
        }
        return projectService.removeProject(projectDTO);
    }

    @PostMapping("/deleteBatch")
    @Operation(summary = "批量删除项目")
    public Result deleteBatch(@RequestBody String[] ids) {
        //获取当前登录用户id
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = user.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")&&!permissions.contains("ROLE_admin")) {
            return Result.error("无权限删除项目!");
        }
        return projectService.removeProjectBatch(Arrays.asList(ids));
    }

    @GetMapping("/all")
    @Operation(summary = "获取所有项目")
    public Result all() {
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Project::getDelFlag, "1");// 查询未删除的项目
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")) {
            queryWrapper.eq(Project::getTenantId, loginUser.getTenantId());
        }
        return Result.success(projectService.list(queryWrapper));
    }

    @PostMapping("/findProjectById")
    @Operation(summary = "根据公司id查询项目")
    public Result findProjectById(@RequestBody String[] tenantIds) {
        List<Project> projectList = projectService.findProjectById(Arrays.asList(tenantIds));
        return Result.success(projectList);
    }

    @PostMapping("/findUserByProjectId")
    @Operation(summary = "根据项目id分角色查询参与该项目的用户")
    public Result findUserByProjectId(@RequestBody Map<String, String> map) {
        String projectId = map.get("projectId");

        ProjectDTO dto = projectService.findUserByProjectId(projectId);
        return Result.success(dto);
    }

    @PostMapping("/getUsersByType")
    @Operation(summary = "根据任务的类型查询未分配任务的用户")
    public Result findUserByProjectId(@RequestBody TaskDTO taskDTO) {
        ProjectDTO dto = projectService.getUsersByType(taskDTO);
        return Result.success(dto);
    }

    @PostMapping("/findUserByProjectTask")
    @Operation(summary = "根据项目id和任务的类型查询对应角色下的用户")
    public Result findUserByProjectTask(@RequestBody Map<String, String> map) {
        String projectId = map.get("projectId");
        String taskType = map.get("taskType");

        ProjectDTO dto = projectService.findUserByProjectTask(projectId, taskType);
        return Result.success(dto);
    }

    @PostMapping("/updateStatus")
    @Operation(summary = "更新项目状态")
    public Result updateStatus(@RequestParam String projectId,
                               @RequestParam String status) {
        Project project = projectService.updateState(projectId, status);
        return Result.success(project);
    }

    @GetMapping("/export")
    @Operation(summary = "导出项目信息")
    public void export(HttpServletResponse response){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        String fileName ="";
        if (!permissions.contains("ROLE_super")) {
            fileName = loginUser.getTenantName()+"项目信息表.xlsx";// 下载时的文件名
        }else{
            fileName = "swpt所有项目信息表.xlsx";// 下载时的文件名
        }
        String sheetName = "项目信息"; // 工作表名称
        List<Project> projects = projectService.all();
        // 调用工具类进行导出
        ExcelUtil.exportExcel(response, fileName, sheetName, Project.class, projects);
    }
    @PostMapping("/import")
    @Operation(summary = "导入项目信息")
    public Result importProject(@RequestParam("file") MultipartFile file) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")&&!permissions.contains("ROLE_admin")) {
            return Result.error("无权限导入项目!");
        }
        if (file.isEmpty()) {
            return Result.error("上传的文件为空");
        }

        try (InputStream inputStream = file.getInputStream()) {
            // 创建监听器
            DataListener<Project> listener =dataListenerFactory.createProjectListener();

            // 读取 Excel
            EasyExcel.read(inputStream, Project.class,listener).sheet().doRead();

            // 获取读取的数据
            List<Project> projectList = listener.getCachedDataList();

            return Result.success("导入成功，导入条数: " + projectList.size());
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("导入过程中出现错误: " + e.getMessage());
        }
    }

    @PostMapping("/update")
    @Operation(summary = "更新项目")
    public Result update(@RequestBody Project project){
        //说明是新增项目
        if(project.getProjectId()==null){
            project.setProjectId(UUID.randomUUID().toString().replace("-",""));
            project.setDelFlag("1");
            project.setProjectStatus("0");
            project.setCreateTime(LocalDateTime.now());
            project.setUpdateTime(LocalDateTime.now());
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            project.setCreateId(loginUser.getUserId());
            project.setUpdateId(loginUser.getUserId());
            return Result.success(projectService.save(project));
        }
        return Result.success(projectService.updateById(project));
    }

    @PostMapping("/add")
    @Operation(summary = "添加项目")
    public Result add(@RequestBody Project project){
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();
        if (!permissions.contains("ROLE_super")&&!permissions.contains("ROLE_admin")) {
            return Result.error("无权限新建项目!");
        }
        project.setDelFlag("1");
        project.setProjectStatus("0");
        project.setCreateId(loginUser.getUsername());
        project.setUpdateId(loginUser.getUsername());
        project.setCreateTime(LocalDateTime.now());
        project.setUpdateTime(LocalDateTime.now());
        return Result.success(projectService.save(project));
    }

    @PostMapping("/search")
    @Operation(summary = "搜索项目")
    public Result search(
            @RequestBody Map map){
        PageBean<Project> pagelist = projectService.search(map);
        return Result.success(pagelist);
    }

    @PostMapping("/findUserByTenantId")
    @Operation(summary = "查询该项目所属租户下的用户")
    public Result findUserByTenantId(@RequestBody Project project) {
        List<User> users = projectService.findUserByTenantIdFilter(project);
        return Result.success(users);
    }

    @PostMapping("/inviteUser")
    @Operation(summary = "邀请项目用户，并判断是否重复邀请")
    public Result inviteUser(@RequestBody InviteProjectUser inviteProjectUser) throws Exception {
        return projectService.inviteUser(inviteProjectUser);
    }

    @PostMapping("/removeUser")
    @Operation(summary = "移除项目用户")
    public Result removeUser(@RequestBody RemoveUserProject removeUserProject) {
        return projectService.removeUser(removeUserProject);
    }

}
